﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Mindfor.Web.Data;
using Mindfor.Web.Models;
using Mindfor.Web.Routing;
using NHibernate;
using NHibernate.Linq;

namespace Mindfor.Web.Mvc.Controllers
{
	/// <summary>
	/// Defines methods for manipulation mail templates: add, edit, delete.
	/// </summary>
	[CmsAuthorize(CmsRoles.MailManager)]
	[PageTitle("Шаблоны писем")]
	public class MailTemplateController : CmsPageController
	{
		/// <summary>
		/// Returns PageResult which renders Index view.
		/// </summary>
		[UrlRoute(1, "")]
		[UrlRouteDefault(1, "page", 1)]
		[UrlRoute(2, "Page{page}")]
		[UrlRouteConstraint(2, "page", Constraints.IsInt)]
		[ManageLink("Шаблоны писем", "Система управления")]
		public ActionResult Index(int page)
		{
			int pageIndex = page - 1;
			int itemsPerPage = 10;
			
			var ts = Data.Query<MailTemplate>();
			ViewData.Model = ts.OrderBy(t => t.Name)
				.Skip(itemsPerPage * pageIndex)
				.Take(itemsPerPage);
			ViewData["Pager"] = new PagerModel(ts.Count(), itemsPerPage);

			Session["MailTemplate.Page"] = page;
			return View();
		}

		/// <summary>
		/// Returns PageResult which renders Edit view with no model.
		/// </summary>
		[LoadFormAndModelState]
		[PageTitle("Добавление")]
		public ActionResult Add()
		{
			return Edit(null);
		}

		/// <summary>
		/// Edits mail template.		
		/// </summary>
		[AcceptVerbs(HttpVerbs.Post)]
		[ValidateInput(false)]
		public ActionResult Add(MailTemplate model, bool? changedIsBodyHtml)
		{
			return Edit(null, model, changedIsBodyHtml);
		}

		/// <summary>
		/// Returns PageResult which renders Edit view.
		/// </summary>
		/// <param name="id">Mail template id to edit. If <c>Null</c>, add new template.</param>
		[UrlRoute("{id}/Edit", false)]
		[UrlRouteConstraint("id", Constraints.IsInt)]
		[LoadFormAndModelState]
		[PageTitle("Изменение")]
		public ActionResult Edit(int? id)
		{
			// find template
			if (id.HasValue)
			{
				MailTemplate t = Data.Get<MailTemplate>(id.Value);
				if (t == null)
					return HttpNotFound();
				ViewData.Model = t;
			}
			
			ViewData["LanguageId"] = Data.Query<Language>()
				.OrderBy(r => r.Name)
				.Select(r => new SelectListItem
					{
						Text = r.Name,
						Value = r.Id.ToString()
					})
				.ToList();
			ViewData["ReturnUrl"] = Url.Action("Index");
			return View("Edit");
		}

		/// <summary>
		/// Edits mail template.		
		/// </summary>
		/// <param name="id">Mail template id to edit. If <c>Null</c>, add new template.</param>
		[AcceptVerbs(HttpVerbs.Post)]
		[ValidateInput(false)]
		public ActionResult Edit(int? id, MailTemplate model, bool? changedIsBodyHtml)
		{
			// if valid
			if (ModelState.IsValid && changedIsBodyHtml != true)
			{
				// TODO: edit and uncomment
				// find item
				//MailTemplate t = null;
				//if (id.HasValue)
				//{
				//    t = Data.Get<MailTemplate>(id.Value);
				//    if (t == null)
				//        return HttpNotFound();
				//}
				//else
				//{
				//    t = new MailTemplate();
				//}
				
				//// update
				//t.Name = model.Name;
				//t.Description = model.Description == "" ? null : model.Description;
				//t.Subject = model.Subject;
				//t.Body = model.Body;
				//t.IsBodyHtml = model.IsBodyHtml;
				//t.LanguageId = model.LanguageId;
				//Data.SubmitChanges();

				// redirect
				return RedirectToAction("Index");
			}
			else
			{
				// clear model state if change IsBodyHtml
				if (changedIsBodyHtml == true)
					ModelState.Clear();

				// save and redirect
				this.SaveFormAndModelState();
				return RedirectToAction(id.HasValue ? "Edit" : "Add");
			}
		}

		/// <summary>
		/// Deletes mail template.
		/// </summary>
		/// <param name="id">Mail template id to de;ete.</param>
		[UrlRoute("{id}/Delete", false)]
		[UrlRouteConstraint("id", Constraints.IsInt)]
		public ActionResult Delete(int id)
		{
			MailTemplate template = Data.Get<MailTemplate>(id);
			if (template == null)
				return HttpNotFound();

			using (ITransaction t = Data.BeginTransaction())
			{
				Data.Delete(template);
				t.Commit();
			}
			return RedirectToAction("Index");
		}
	}
}
